package com.joint.web.action.app;

import com.fz.us.base.bean.BaseEnum;
import com.fz.us.base.bean.Pager;
import com.fz.us.base.util.DataUtil;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.joint.base.bean.EnumManage;
import com.joint.base.entity.Comment;
import com.joint.base.entity.FileManage;
import com.joint.base.entity.Users;
import com.joint.base.service.CommentService;
import com.joint.base.service.FileManageService;
import com.joint.base.service.UsersService;
import com.joint.core.entity.ProBack;
import com.joint.core.entity.ProInfo;
import com.joint.core.service.AnnounceService;
import com.joint.core.service.KnowledgeService;
import com.joint.core.service.ProBackService;
import com.joint.core.service.ProInfoService;
import com.joint.web.action.BaseAction;
import com.opensymphony.xwork2.ModelDriven;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.convention.annotation.ParentPackage;

import javax.annotation.Resource;
import java.util.*;

/**
 * 后台Action类 - 批注管理
 */
@ParentPackage("app")
public class CommentAction extends BaseAction implements ModelDriven<Comment> {

    private static final long serialVersionUID = -3957546401899874034L;

    private Comment comment;
	private List<Comment> commentList;
    private String ctargetId;   //comment target id

    @Resource
    private UsersService usersService;
	@Resource
	private CommentService commentService;
    @Resource
    private ProInfoService proInfoService;
    @Resource
    private ProBackService probackService;
    @Resource
    private KnowledgeService knowledgeService;
    @Resource
    private AnnounceService announceService;
    @Resource
    private FileManageService fileManageService;

    /**
     * 创建批注
     *
     * @return String
     * @throws Exception
     */
    public String create() throws Exception {
        users = getRequestUsers();
        company = users.getCompany();
        if(company == null)
            return ajaxHtmlAppResult(0, "未找到用户所属企业！",null);

        if(StringUtils.isEmpty(comment.getText())){
            return ajaxHtmlAppResult(0, "批注不能为空！",null);
        }
        String targetId = comment.getTargetId();
        String targetClass = comment.getTargetClass();
        if(StringUtils.isEmpty(targetId)||StringUtils.isEmpty(targetClass)){
            return ajaxHtmlAppResult(0, "批注对象不能为空！",null);
        }
        Set<Users> toUsers = Sets.newHashSet();
        if(StringUtils.isNotEmpty(comment.getAtUsers())){
            String usersIds[] = comment.getAtUsers().split(",");
            for(String toUsersId:usersIds){
                toUsers.add(usersService.get(toUsersId));
            }
        }else{
            if(targetClass.contains("ProBack") || targetClass.contains("ProInfo")){
                ProInfo proInfo;
                if(targetClass.contains("ProBack")){
                    ProBack proBack = probackService.get(targetId);
                    proInfo = proBack.getProInfo();
                }else{
                    proInfo = proInfoService.get(targetId);
                }
                toUsers.add(proInfo.getCreater());
                toUsers.add(proInfo.getChief());
                Set<Users> group = proInfo.getGroup();
                if(group!=null && group.size()>0){
                    for(Users u : group){
                        toUsers.add(u);
                    }
                }
            }
        }
//        LogUtil.info("{toUsers}"+toUsers.size());
        comment.setCreater(users);
        comment.setCompany(company);
        comment.setModel(EnumManage.CommentModelEnum.text);
        comment.setIfAgree(0);
        comment.setIfFeedbackChecked(0);
        comment.setIfRead(0);
        comment.setIfSystem(0);
        comment.setCommentState(EnumManage.CommentState.response);
        comment.setType(EnumManage.CommentTypeEnum.none);
        comment = commentService.createNewCommentApp(comment, toUsers);

        if(StringUtils.isNotEmpty(comment.getId())){
            return ajaxHtmlAppResult(1, "提交成功！", null);
        }else{
            return ajaxHtmlAppResult(0, "提交失败！",null);
        }
    }

    /**
     * 单个List项目
     * @param comment
     * @return
     */
    public Map<String, String> getListItemMap(Comment comment) {
        Map<String,String> map = new HashMap<String,String>();

        String subject = "无主题";
        String name = "无项目";
        String type = "";
        if(comment.getTargetClass()!=null){

            if(comment.getTargetClass().equalsIgnoreCase("com.joint.core.entity.ProInfo")){
                subject = "[项目信息表]"+proInfoService.get(comment.getTargetId()).getName();
                name = proInfoService.get(comment.getTargetId()).getName();
                type = "proinfo";
            }else if(comment.getTargetClass().equalsIgnoreCase("com.joint.core.entity.ProBack")){
                subject = "[项目反馈表]"+probackService.get(comment.getTargetId()).getName();
                name = probackService.get(comment.getTargetId()).getProInfo().getName();
                type = "proback";
            }else if(comment.getTargetClass().equalsIgnoreCase("com.joint.core.entity.Knowledge")){
                subject = "[知识库文档]"+knowledgeService.get(comment.getTargetId()).getName();
                type = "knowledge";
            }else if(comment.getTargetClass().equalsIgnoreCase("com.joint.core.entity.Announce")){
                subject = "[公告信息表]"+announceService.get(comment.getTargetId()).getName();
                type = "announce";
            }

        }

        map.put("subject", subject);
        map.put("projectName", name);
        map.put("type", type);

        map.put("id", StringUtils.isNotEmpty(comment.getId())?comment.getId():"");

        String names = "";
        if (StringUtils.isNotEmpty(comment.getAtUsers())) {
            for (String s : comment.getAtUsers().split(",")) {
                Users u = usersService.get(s);
                names += "@" + u.getName() + ",";
            }
            names = names.substring(0,names.length()-1);
        }
        map.put("atUsersName", names);
        map.put("text", comment.getText());

        map.put("createDate", DataUtil.DateTimeToString(comment.getCreateDate()));
        map.put("modifyDate", DataUtil.DateTimeToString(comment.getModifyDate()));
        if(comment.getCreater()!=null){
            Users creater = comment.getCreater();
            map.put("createrId", creater.getId());
            map.put("createrName", creater.getName());
            map.put("mobile", creater.getMobile());
            map.put("createrFace", getCreaterFaceId(creater.getId()));
        }else{
            map.put("createrId", "");
            map.put("createrName", "");
            map.put("mobile", "");
            map.put("createrFace", "");
        }

        map.put("targetId", StringUtils.isNotEmpty(comment.getTargetId())?comment.getTargetId():"");
        map.put("targetClass", StringUtils.isNotEmpty(comment.getTargetClass())?comment.getTargetClass():"");

        return map;
    }

    private String getCreaterFaceId(String uid){
        String faceId = "";
        List<FileManage> manageList = fileManageService.getFileByKeyId(uid);
        if(manageList.size()>0){
            faceId = uid;
        }
        return faceId;
    }

    public Map<String, Object> getDetailMap(Comment comment) {
        return null;
    }

    /**
	 * 批注列表
	 * @return String
	 * @throws Exception
	 */
	public String getList() throws Exception {

        pager = new Pager();
        pager.setPageNumber(pageIndex);// 页码
        pager.setPageSize(pageSize);// 页Size
        if(StringUtils.isNotEmpty(pageProperty)&&StringUtils.isNotEmpty(pageKeyword)){
            pager.setProperty(pageProperty);
            pager.setKeyword(pageKeyword);
        }
        pager.setOrderBy("createDate");
        pager.setOrderType(BaseEnum.OrderType.desc);

        Map<String, Object> map;
        map = Maps.newHashMap();
        map.put("name", pageKeyword);
        map.put("company", usersService.getCompanyByUser());
        map.put("state", new BaseEnum.StateEnum[]{BaseEnum.StateEnum.Enable});
        pager = commentService.findByPager(pager,map);
//        LogUtil.info("size:" + pager.getList().size());
        commentList = (List<Comment>) pager.getList();
        if(commentList == null){
            commentList = new ArrayList<Comment>();
        }

        List<JSONObject> dataRows = new ArrayList<JSONObject>();
        Map<String, Object> data = new HashMap<String, Object>();

        for (Comment temp : commentList) {
            Map<String, String> tempMap = getListItemMap(temp);
            dataRows.add(JSONObject.fromObject(tempMap));
        }

        data.put("pageNum", pageIndex);//页数
        data.put("pageSize", commentList.size());//记录数
        data.put("pageCount", pager.getPageCount());//总页数
        data.put("totalCount", pager.getTotalCount());//总记录数
        data.put("dataRows", JSONArray.fromObject(dataRows));//数据

        return ajaxHtmlAppResult(1, "", JSONObject.fromObject(data));
	}

    /**
     * 某一文档下的批注列表
     * @return String
     * @throws Exception
     */
    public String getAboutTargetList() throws Exception {

        pager = new Pager();
        pager.setPageNumber(pageIndex);// 页码
        pager.setPageSize(pageSize);// 页Size

        pager.setOrderBy("createDate");
        pager.setOrderType(BaseEnum.OrderType.asc);

        Map<String, Object> map;
        map = Maps.newHashMap();
//        map.put("name", pageKeyword);
//        map.put("company", usersService.getCompanyByUser());
//        LogUtil.info("{ctargetId}"+ctargetId);
        if(StringUtils.isNotEmpty(ctargetId)){
            map.put("targetId",ctargetId);
        }else{
            map.put("targetId","null");
        }
        map.put("state", new BaseEnum.StateEnum[]{BaseEnum.StateEnum.Enable});
        pager = commentService.findByPager(pager,map);
//        LogUtil.info("size:" + pager.getList().size());
        commentList = (List<Comment>) pager.getList();
        if(commentList == null){
            commentList = new ArrayList<Comment>();
        }

        List<JSONObject> dataRows = new ArrayList<JSONObject>();
        Map<String, Object> data = new HashMap<String, Object>();

        for (Comment temp : commentList) {
            Map<String, String> tempMap = getListItemMap(temp);
            dataRows.add(JSONObject.fromObject(tempMap));
        }

        data.put("pageNum", pageIndex);//页数
        data.put("pageSize", commentList.size());//记录数
        data.put("pageCount", pager.getPageCount());//总页数
        data.put("totalCount", pager.getTotalCount());//总记录数
        data.put("dataRows", JSONArray.fromObject(dataRows));//数据

        return ajaxHtmlAppResult(1, "", JSONObject.fromObject(data));
    }

    /**
     * 我的批注动态
     *
     * @return String
     * @throws Exception
     */
    public String getAboutMeList() throws Exception {
        users = getRequestUsers();
        company = users.getCompany();
        if(company == null)
            return ajaxHtmlAppResult(0, "未找到用户所属企业！",null);

        pager = new Pager();
        pager.setPageNumber(pageIndex);// 页码
        pager.setPageSize(pageSize);// 页Size
        pager.setOrderType(BaseEnum.OrderType.desc);
        pager.setOrderBy("createDate");

        List<JSONObject> dataRows = new ArrayList<JSONObject>();
        Map<String, Object> data = new HashMap<String, Object>();

        //toUsers中是我
//        pager = commentService.getPager(pager, null, users, "", "", -1, -1, null, null, BaseEnum.StateEnum.Enable);
//        commentList = (List<Comment>) pager.getList();
//        if (commentList == null) {
//            commentList = new ArrayList<Comment>();
//        }else{
//            for (Comment temp : commentList) {
//                dataRows.add(JSONObject.fromObject(getListItemMap(temp)));
//            }
//        }

        //creater是我,或atUsers中有我
        pager = commentService.getPager(pager, users, null, "", "", -1, -1, null, null, BaseEnum.StateEnum.Enable);
        commentList = (List<Comment>) pager.getList();
        if (commentList != null) {
            for (Comment temp : commentList) {
                dataRows.add(JSONObject.fromObject(getListItemMap(temp)));
            }
        }

        data.put("pageNum", pageIndex);//页数
        data.put("pageSize", commentList.size());
        data.put("pageCount", pager.getPageCount());
        data.put("totalCount", pager.getTotalCount());
        data.put("dataRows", JSONArray.fromObject(dataRows));
        return ajaxHtmlAppResult(1, "", JSONObject.fromObject(data));
    }

	/**
	 * 批注详情
     *
	 * @return String
	 * @throws Exception
	 */
	public String getDetail() throws Exception {

        if (StringUtils.isNotEmpty(keyId)) {
            comment = commentService.get(keyId);
            if (comment != null) {
                Map<String, Object> data = getDetailMap(comment);
                return ajaxHtmlAppResult(1, "", JSONObject.fromObject(data));
            }
        }
        return ajaxHtmlAppResult(0, "无法找到该文档，可能已被删除！", null);
	}

	@Override
	public Comment getModel() {
		if(comment == null){
            comment = new Comment();
		}
		return comment;
	}

    public String getCtargetId() {
        return ctargetId;
    }

    public void setCtargetId(String ctargetId) {
        this.ctargetId = ctargetId;
    }

    public Comment getComment() {
        return comment;
    }

    public void setComment(Comment comment) {
        this.comment = comment;
    }
}
